import json
import logging
import yaml
import requests
from auto.apiSecurity.common.basic import encrypt_with_aes, decrypt_with_aes, owner_check


def add_project(env, project_name, prefix, app_id):
    with open('data/config/token.yml', 'r') as f:
        config = yaml.safe_load(f)
    with open('data/config/config.yaml', 'r') as f2:
        config_data = yaml.safe_load(f2)

    url = config_data['environments'][env]['host'] + config_data['environments'][env]['add_project']
    token = config['token']
    owner = str(owner_check(env))
    headers = {'Content-Type': 'application/json', 'version': '2.0', 'Authorization': token}
    query_params = {
    }
    payload = {
        "projectName": project_name,
        "prefix": prefix,
        "appId": app_id,
        "authType": "none",
        "projectPolicyViews": [],
        "portalOpen": True,
        "authConfig": "{}",
        "owner": owner
    }
    data = json.dumps(payload)
    encrypt_payload = encrypt_with_aes(data, "63474e6489b45592")
    # print(encrypt_payload)
    try:
        # 发送 POST 请求
        response = requests.post(url, data=encrypt_payload, headers=headers, params=query_params)
        # 检查响应状态
        response.raise_for_status()  # 如果响应状态码不是 200，抛出异常
        # 拿到加密报文
        encrypted_response_body = response.content
        # 报文解密
        decrypted_response_body = decrypt_with_aes(encrypted_response_body, '63474e6489b45592')
        # 尝试解析解密后的内容为 JSON 对象
        try:
            parsed_data = json.loads(decrypted_response_body)
        except json.JSONDecodeError as e:
            logging.error("解析 JSON 失败: %s", str(e))
            return

        assert parsed_data.get('code') == "200", f"响应不成功: {parsed_data.get('msg')}"
        logging.info("成功----" + project_name + "项目创建成功")
    except requests.exceptions.RequestException as e:
        logging.error("请求失败: %s", str(e))
    except AssertionError as e:
        logging.error("断言失败: %s", str(e))
    except Exception as e:
        logging.error("发生错误: %s", str(e))
